package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.mapper.UserMapper;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import com.example.demo.utils.Md5Util;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    //继承了基本的逻辑，可以在此处添加其他逻辑
    //登录
    public Integer Login(String userAccount, String userPassword){
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        User user = this.baseMapper.selectOne(queryWrapper);
        boolean res=Md5Util.verifySaltPassword(userPassword,user.getUserPassword());
        // 用户不存在
        if (user == null) {
            return 404;
        }
        if(!res){
            return 405;
        }
        // 3. 记录用户的登录态
        return 200;
    }
    //判断用户是否存在
    public Integer ExistAccount(String userAccount){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        User user = this.baseMapper.selectOne(queryWrapper);
        if(user == null){
            return 1;
        }
        return 0;
    }
    //注册
    public long Register(User user){
        this.save(user);
        return user.getId();
    }

    public User GetInfo(String userAccount) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        User user = this.baseMapper.selectOne(queryWrapper);
        return user;
    }

    public boolean Update(String userAccount, String email, String password, Date updateTime) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        User user = this.baseMapper.selectOne(queryWrapper);
        user.setUpdateTime(updateTime);
        user.setUserPassword(password);
        user.setEmail(email);
        // 更新用户信息
        int result = this.baseMapper.updateById(user);

        // 返回更新是否成功
        return result > 0;
    }

    public int GetUserId(String userAccount) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        User user = this.baseMapper.selectOne(queryWrapper);
        return user.getId();
    }
}
